import 'package:flutter/material.dart';

/// 间隔两秒才能点击的按钮
class WJFutureDetector extends StatefulWidget {
  // 子组件
  final Widget? child;

  /// 点击回调事件
  final VoidCallback? onTap;

  /// 点击超时回调事件, 即恢复了可点击状态的回调
  final VoidCallback? onTapTimeOut;

  /// 点击回调事件
  final GestureTapDownCallback? onTapDown;

  /// 点击回调事件
  final VoidCallback? onTapCancel;

  /// 点击回调事件
  final GestureTapUpCallback? onTapUp;

  final HitTestBehavior behavior;

  final Duration delayDuration; // ms

  // 扩展点击事件
  final EdgeInsets? extraHitTestArea;

  const WJFutureDetector({
    super.key,
    this.child,
    this.onTap,
    this.onTapTimeOut,
    this.onTapCancel,
    this.onTapDown,
    this.onTapUp,
    this.delayDuration = const Duration(seconds: 1),
    this.behavior = HitTestBehavior.deferToChild,
    this.extraHitTestArea,
  });

  @override
  DelayButtonState createState() => DelayButtonState();
}

class DelayButtonState extends State<WJFutureDetector> {
  /// 按钮可点击
  bool enabled = true;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: widget.behavior,
      onTap: _onTap,
      onTapDown: widget.onTapDown,
      onTapCancel: widget.onTapCancel,
      onTapUp: widget.onTapUp,
      child: _childContainer(),
    );
  }

  DateTime? callTime;

  _onTap() {
    if (callTime == null) {
      callTime = DateTime.now();
      widget.onTap?.call();
    } else {
      if (DateTime.now().difference(callTime!) > widget.delayDuration) {
        callTime = DateTime.now();
        return widget.onTap?.call();
      } else {
        print("not responed!");
      }
    }
    // Timer(widget.delayDuration, () {
    //   enabled = true;
    //   return widget.onTapTimeOut?.call();
    // });
    // if (enabled) {
    //   enabled = false;
    //   return widget.onTap?.call();
    //   // track
    //   if (widget.track != null && widget.track.eventName != null) {
    //     TATrack().trackMap(widget.track.eventName, properties: widget.track.getParams());
    //   }
    // } else {
    //   logger.v('button is not enable');
    // }
  }

  Widget _childContainer() {
    return Container(
      decoration: BoxDecoration(color: Colors.transparent),
      child: widget.child,
    );
  }
}
